import uniq from 'lodash/uniq';
import Post from '../../../Models/post';
import PostMsg from '../../../Models/postMsg';
import PostLike from '../../../Models/postLike';
import User2Post from '../../../Models/user2Post';
import User2User from '../../../Models/user2User';
import { getCreator } from '../../../utils/util';
import { saveNotice, getNewPoints } from '../utils/';
import moment from 'moment';
import { getPoints } from '../goods';

const postEntity = new Post();
const postMsgEntity = new PostMsg();
const postLikeEntity = new PostLike();
const user2PostEntity = new User2Post();
const user2UserEntity = new User2User();

export function getPosts(req, res, next) {
    const {  userId, ...query } = req.body;
    if (!query.type) {
        query.type = 0;
    }
    if (query.type === 'all') {
       delete query.type;
    }
    if (!userId) {
        postEntity.getPosts(query, (err, posts, total, hasMore) => {
            if (err) {
                return res.status(200).json({ code: 1, msg: '服务器开小差' });
            }
            return res.status(200).json({ code: 0, data: { list: posts, total, hasMore } });
        })
    } else {
        user2PostEntity.getAllUser2Posts({userId}, (err, u2ps)=>{
            if (u2ps.length) {
                query._id = {
                    $nin: u2ps.map(u=>u.postId)
                }
            }
            postEntity.getPosts(query, (err, posts, total, hasMore) => {
                if (err) {
                    return res.status(200).json({ code: 1, msg: '服务器开小差' });
                }
                return res.status(200).json({ code: 0, data: { list: posts, total, hasMore } });
            })
        })
    }
}

export function getBest10List(req, res, next) {
    const start = moment({ hour: 0, minute: 0, second: 0 }).unix();
    const end = moment({ hour: 23, minute: 59, second: 59 }).unix();
    const query = { createTime: { $gt: start, $lt: end } }
    postEntity.getBest10Posts(query, (err, posts) => {
        if (err) {
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        return res.status(200).json({ code: 0, data: { list: posts, total: 10, hasMore: false } });
    })
}

export function getActivities(req, res, next) {
    const {  ...query } = req.body;
    query.type = { "$in":[1, 2] }
    
    postEntity.getPosts(query, (err, posts, total, hasMore) => {
        if (err) {
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        return res.status(200).json({ code: 0, data: { list: posts, total, hasMore } });
    })
}


export function getPost(req, res, next) {
    const {  ...query } = req.body;
    const creator = getCreator(req.user);
    postEntity.getPost(query, (err, post) => {
        if (err) {
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        if (!post) {
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        const data = post._doc;
        const postId = data._id.toString()
        postMsgEntity.getPostMsgs({postId: data._id, current: 1, pageSize: 10}, (err, cmts, count, hasMore) => {
            if (err) {
                return res.status(200).json({ code: 1, msg: '服务器开小差' });
            }
            postLikeEntity.getAllPostLikes({postId}, (err, likes) => {
                if (err) {
                    return res.status(200).json({ code: 1, msg: '服务器开小差' });
                }
                cmts = cmts.map(c=>{
                    c = c._doc;
                    if ((c.likes || {})[creator._id]) {
                        c.hasLike = true
                    } else {
                        c.hasLike = false
                    }
                    delete c.likes;
                    return c;
                })
                
                data.cmt = {cmts, hasMore, count};
                data.likes = likes || [];
                return res.status(200).json({ code: 0, data });
            })
        })
    })
}

export function getMorePostMsgs(req, res, next) {
    const {  ...query } = req.body;
    postMsgEntity.getPostMsgs(query, (err, cmts, count, hasMore) => {
        if (err) {
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        const creator = getCreator(req.user);
        cmts.forEach(c=>{
            if ((c.like || {})[creator._id]) {
                c.hasLike = true
            } else {
                c.hasLike = false
            }
            delete c.likes;
        })
        const data = {
            cmts, count, hasMore
        }
        return res.status(200).json({ code: 0, data });
    })
}

export function getAllPostLikes(req, res, next) {
    const {  ...query } = req.body;
    postLikeEntity.getAllPostLikes(query, (err, likes) => {
        if (err) {
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        return res.status(200).json({ code: 0, data: likes });
    })
}

export function createPost(req, res, next) {
    const {  ...post } = req.body;
    const postEntity = new Post();
    const creator = getCreator(req.user);
    post.creatorId = creator._id;
    post.creator = creator;
    postEntity.savePost(post, err => {
        if (err) {
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        // if (post.content.length>=70 || post.imgs[0]) {
        //     getNewPoints (creator._id, '发布帖子', 10) 
        // } else {
        //     getNewPoints (creator._id, '发布帖子', 1) 
        // }
        getNewPoints (creator._id, '发布帖子', 10) 
        return res.status(200).json({ code: 0 });
    });
}

export function updatePost(req, res, next) {
    const {  ...post } = req.body;
    const postEntity = new Post();
    if (!post._id) {
        postEntity.savePost(post, err => {
            if (err) {
                return res.status(200).json({ code: 1, msg: '服务器开小差' });
            }
            return res.status(200).json({ code: 0 });
        });
    } else {
        postEntity.updatePost(post, err => {
            if (err) {
                return res.status(200).json({ code: 1, msg: '服务器开小差' });
            }
            return res.status(200).json({ code: 0 });
        });
    }
}

export function removePost(req, res, next) {
    const {  _id } = req.body;
    postEntity.updatePost({_id, isDeleted: true}, (err) => {
        if (err) {
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        return res.status(200).json({ code: 0 });
    });
}



export function setTopPost(req, res, next) {
    const { _id, isTop } = req.body;
    postEntity.updatePost({_id, isTop}, err => {
        if (err) {
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        return res.status(200).json({ code: 0 });
    });
}

export function noPassPost(req, res, next) {
    const { _id } = req.body;
    postEntity.updatePost({_id, isAuth: false}, err => {
        if (err) {
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        return res.status(200).json({ code: 0 });
    });
}

export function removePosts(req, res, next) {
    const postIds = req.body.postIds;
    postEntity.removePosts(postIds, (err, post) => {
        if (err) {
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        return res.status(200).json({ code: 0 });
    });
}

export function likePost(req, res, next) {
    let { postId } = req.body;
    const creator = getCreator(req.user)
    postEntity.getPost({ _id: postId }, (err, post) => {
        if (err) {
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        postLikeEntity.getPostLike({postId, creatorId: creator._id}, (err, like) => {
            if (err) {
                return res.status(200).json({ code: 1, msg: '服务器开小差' });
            }
            if (like) {
                const postMsgId = like._id.toString()
                postLikeEntity.removePostLikes([postMsgId], err=>{
                    if (err) {
                        return res.status(200).json({ code: 1, msg: '服务器开小差' });
                    }
                    const likeNum = (post.likeNum || 0) - 1;
                    postEntity.updatePost({_id: post._id, likeNum}, err => {
                        if (err) {
                            return res.status(200).json({ code: 1, msg: '服务器开小差' });
                        }
                        return res.status(200).json({ code: 0 });
                    });
                })
                return;
            }
            const newLike = {
                postId,
                postContent: post.content,
                postCreateTime: post.createTime,
                type: post.type,
                creatorId: creator._id,
                creator
            }
            postLikeEntity.savePostLike(newLike, err => {
                if (err) {
                    return res.status(200).json({ code: 1, msg: '服务器开小差' });
                }
                const data = post._doc;
                const notice = {
                    receiverId: data.creator._id,
                    receiver: data.creator,
                    url: '/detail/'+postId,
                    msg: `有人赞了您的帖子《${data.content}》`,
                    type: 'like',
                    status: 0,
                }
                saveNotice(notice);
                getNewPoints (creator._id, '点赞帖子', 1);
                const likeNum = (data.likeNum || 0) + 1;
                postEntity.updatePost({_id: data._id, likeNum}, err => {
                    if (err) {
                        return res.status(200).json({ code: 1, msg: '服务器开小差' });
                    }
                    return res.status(200).json({ code: 0 });
                });
            });
        })
    })
}

export function removePostMsgs(req, res, next) {
    const postMsgIds = req.body.postMsgIds;
    postMsgEntity.removePostMsgs(postMsgIds, (err, post) => {
        if (err) {
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        return res.status(200).json({ code: 0 });
    });
}

export function getPostMsgs(req, res, next) {
    const {  ...query } = req.body;
    postMsgEntity.getPostMsgs(query, (err, posts, total, hasMore) => {
        if (err) {
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        return res.status(200).json({ code: 0, data: {list: posts, total, hasMore} });
    });
}



export function cmtPost(req, res, next) {
    let {  postId, cmt } = req.body;
    const creator = getCreator(req.user)

    postEntity.getPost({ _id: postId }, (err, post) => {
        if (err) {
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        const data = post._doc;
        const postMsgEntity = new PostMsg();
        postMsgEntity.savePostMsg({content: cmt,postId, creator}, (err, cmts) => {
            if (err) {
                return res.status(200).json({ code: 1, msg: '服务器开小差' });
            }
            data.cmtNum = (data.cmtNum || 0) + 1;
            postEntity.updatePost(data, err => {
                if (err) {
                    return res.status(200).json({ code: 1, msg: '服务器开小差' });
                }
                const notice = {
                    receiverId: data.creator._id,
                    receiver: data.creator,
                    url: '/detail/'+postId,
                    msg: `有人评论了您的帖子《${data.content}》`,
                    type: 'cmt',
                    status: 0
                }
                saveNotice(notice);
                getNewPoints (creator._id, '评论帖子', 1) 
                return res.status(200).json({ code: 0 });
            });
        })
    })
}

export function joinActivity(req, res, next) {
    let {  postId, content } = req.body;
    const creator = getCreator(req.user)

    postEntity.getPost({ _id: postId }, (err, post) => {
        if (err) {
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        const postJoinEntity = new PostJoin();
        postJoinEntity.savePostJoin({content,postId, creator, creatorId: creator._id}, (err) => {
            if (err) {
                return res.status(200).json({ code: 1, msg: '服务器开小差' });
            }
            const obj = {
                _id: post._id,
                joinNum: (post.joinNum || 0) + 1
            }
            postEntity.updatePost(obj, err => {
                if (err) {
                    return res.status(200).json({ code: 1, msg: '服务器开小差' });
                }
                return res.status(200).json({ code: 0 });
            });
        })
    })
}

export function sharePost(req, res, next) {
    let {  postId } = req.body;

    postEntity.getPost({ _id: postId }, (err, post) => {
        if (err) {
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        const notice = {
            receiverId: post.creator._id,
            receiver: post.creator,
            url: '/detail/'+postId,
            msg: `有人分享了您的帖子《${post.content}》`,
            type: 'share',
            status: 0,
        }
        saveNotice(notice);
        postEntity.updatePost({_id: postId, shareNum: (post.shareNum || 0) + 1}, err => {
            if (err) {
                return res.status(200).json({ code: 1, msg: '服务器开小差' });
            }
            return res.status(200).json({ code: 0 });
        });
    })
}

export function unWatchPost(req, res, next) {
    const { postId } = req.body;
    const creator = getCreator(req.user)
    const data = {
        userId: creator._id,
        postId
    }
    user2PostEntity.getUser2Post(data, (err, u2p)=>{
        if (u2p) {
            return res.status(200).json({ code: 1, msg: '已经不在关注这个帖子' });
        }
        user2PostEntity.saveUser2Post(data, (err) => {
            if (err) {
                return res.status(200).json({ code: 1, msg: '服务器开小差' });
            }
            return res.status(200).json({ code: 0 });
        })
    })
}

export function getMyLikePosts(req, res, next) {
    const creator = getCreator(req.user)
    postLikeEntity.getAllPostLikes({creatorId: creator._id}, (err, postlikes) => {
        if (err) {
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        return res.status(200).json({ code: 0, data: postlikes });
    })
}

export function getMyWatchPost(req, res, next) {
    const creator = getCreator(req.user)
    user2UserEntity.getAllUser2Users({userId: creator._id}, (err, user2Users) => {
        if (err) {
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        const query = { creatorId: { "$in": user2Users.map(u=>u.user2Id) } }
        postEntity.getPosts(query, (err, posts, total, hasMore) => {
            if (err) {
                return res.status(200).json({ code: 1, msg: '服务器开小差' });
            }
            return res.status(200).json({ code: 0, data: { list: posts, total, hasMore } });
        })
    })
}

export function addCourse(req, res, next) {
    const { title, content, college ,cmt, tags = [], scores, courseObj } = req.body;
    const creator = getCreator(req.user);
    postEntity.getPost({title, content, college, type: 3}, (err, courses) => {
        if (err) {
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        if (courses) {
            return res.status(200).json({ code: 1, msg: '该课程已存在' });
        }
        const postEntity = new Post();
        const tagsObj = tags.reduce((t,c)=>{
            t[c] = 1
            return t;
        }, {});
        postEntity.savePost({title, content, college, tags: tagsObj, scores, creatorId: creator._id, creator, type: 3, cmtNum: 1, courseObj}, (err, posts) => {
            if (err) {
                return res.status(200).json({ code: 1, msg: '服务器开小差' });
            }
            if (!cmt) {
                return res.status(200).json({ code: 0 });
            }
            getNewPoints (creator._id, '发布帖子', 10) 
            const postMsg = {
                content: cmt,
                postId:  posts[0]._id,
                creatorId: creator._id,
                creator,
                scores,
                tags,
            }
            const postMsgEntity = new PostMsg();
            postMsgEntity.savePostMsg(postMsg, (err) => {
                if (err) {
                    return res.status(200).json({ code: 1, msg: '服务器开小差' });
                }
                return res.status(200).json({ code: 0 });
            })
        });
    });
}


export function cmtCourse(req, res, next) {
    let {  postId, cmt, scores = [], tags = [] } = req.body;
    const creator = getCreator(req.user)
    postEntity.getPost({ _id: postId }, (err, post) => {
        if (err) {
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        if (!cmt) {
            const newPost = {
                _id: postId,
            }

            const allTags = post.tags;
            newPost.tags = tags.reduce((t,c)=>{
                if (t[c]) {
                    t[c]++;
                } else {
                    t[c] = 1;
                }
                return t;
            }, allTags);
            newPost.scores = post.scores.map((s, i)=>(s*post.cmtNum+scores[i])/(post.cmtNum+1));
            newPost.cmtNum = post.cmtNum + 1;
            newPost.likes = {'fordelete': true};
            postEntity.updatePost(newPost, err => {
                if (err) {
                    return res.status(200).json({ code: 1, msg: '服务器开小差' });
                }
                return res.status(200).json({ code: 0 });
            });
        } else {
            const postMsg = {
                content: cmt,
                postId,
                creatorId: creator._id,
                creator,
                scores,
                tags,
            }
            const postMsgEntity = new PostMsg();
            postMsgEntity.savePostMsg(postMsg, (err) => {
                if (err) {
                    return res.status(200).json({ code: 1, msg: '服务器开小差' });
                }
                const newPost = {
                    _id: postId,
                }
                const allTags = post.tags;
                newPost.tags = tags.reduce((t,c)=>{
                    if (t[c]) {
                        t[c]++;
                    } else {
                        t[c] = 1;
                    }
                    return t;
                }, allTags);
                newPost.scores = post.scores.map((s, i)=>(s*post.cmtNum+scores[i])/(post.cmtNum+1));
                newPost.cmtNum = post.cmtNum + 1;
                newPost.likes = {'fordelete': true};
                postEntity.updatePost(newPost, err => {
                    if (err) {
                        return res.status(200).json({ code: 1, msg: '服务器开小差' });
                    }
                    getNewPoints (creator._id, '评论帖子', 1) 
                    return res.status(200).json({ code: 0 });
                });
            })
        }
    })
}

export function searchPosts(req, res, next) {
    const { keyword, type = 0 } = req.body;
    const query = {"$or":[{
        title: {
            $regex: keyword,
            $options: "i"
          }
    }, {
        content: {
            $regex: keyword,
            $options: "i"
          }
    }],
    type};

    postEntity.getPosts(query, (err, posts, total, hasMore) => {
        if (err) {
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        return res.status(200).json({ code: 0, data: { list: posts, total, hasMore } });
    })
}

export function viewPost(req, res, next) {
    let { postId } = req.body;

    postEntity.getPost({ _id: postId }, (err, post) => {
        if (err) {
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        post.viewNum = (post.viewNum || 0) + 1;
        postEntity.updatePost(post, err => {
            if (err) {
                return res.status(200).json({ code: 1, msg: '服务器开小差' });
            }
            return res.status(200).json({ code: 0 });
        });
    })
}

export function likePostMsg(req, res, next) {
    const { _id } = req.body;
    const creator = getCreator(req.user)
    postMsgEntity.getPostMsg({_id}, (err, postMsg) => {
        if (err) {
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        if (!postMsg) {
            return res.status(200).json({ code: 1, msg: '服务器开小差' });
        }
        const { likeNum = 0, likes = {} } = postMsg;
        const newPostMsg = {
            _id
        }
        if (likes[creator._id]) {
            delete likes[creator._id]; 
            newPostMsg.likeNum = likeNum - 1;
        } else {
            likes[creator._id] = true; 
            newPostMsg.likeNum = likeNum + 1;
            getNewPoints (creator._id, '点赞帖子', 1) 
        }
        newPostMsg.likes = likes;
        postMsgEntity.updatePostMsg(newPostMsg, (err) => {
            if (err) {
                return res.status(200).json({ code: 1, msg: '服务器开小差' });
            }
            postEntity.getPost({_id: postMsg.postId}, (err, post)=>{
                if (post) {
                    const notice = {
                        receiverId: post.creator._id,
                        receiver: post.creator,
                        url: '/detail/'+postMsg.postId,
                        msg: `有人赞了您的评论`,
                        type: 'like',
                        status: 0,
                    }
                    saveNotice(notice);
                }
            })
            return res.status(200).json({ code: 0 });
        })
    })
}



